package com.zyb.lmbackend.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import java.io.InputStream;
import java.util.Set;

/**
 * 使用 JSON Schema 对 LLM 输出进行结构校验的工具类。
 */
public class JsonSchemaValidatorUtil {

    private final ObjectMapper mapper;
    private final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();

    public JsonSchemaValidatorUtil(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    /**
     * 遍历逐条校验，若任一失败则抛出异常。
     * @param nodes 待校验节点序列
     * @param classpathSchema 类路径下的 schema 文件路径
     */
    public void validateEach(Iterable<JsonNode> nodes, String classpathSchema) throws ProcessingException {
        JsonSchema schema = loadSchema(classpathSchema);
        int idx = 0;
        for (JsonNode node : nodes) {
            idx++;
            ProcessingReport report = schema.validate(node);
            if (!report.isSuccess()) {
                throw new InvalidLlmOutputException("Schema 校验失败 @ item " + idx + ": " + report.toString());
            }
        }
    }

    /** 从类路径加载并编译 Schema。 */
    private JsonSchema loadSchema(String path) {
        try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path)) {
            if (is == null) throw new IllegalArgumentException("未找到 Schema: " + path);
            JsonNode node = mapper.readTree(is);
            return factory.getJsonSchema(node);
        } catch (Exception e) {
            throw new RuntimeException("加载 Schema 失败: " + path, e);
        }
    }
}
